/**   
* @Title: ChargeListAct.java 
* @Package: com.esun.rabbit2.viewer.mainact.mylotteryact.accountdetail 
* @Description: TODO(账户明细充值列表activity) 
* @Author: Billy qigs@500wan.com   
* @Date: 2011-7-27 下午04:48:59  
* Copyright (C) 2011 Shenzhen E-sun Sky Net Technology Co.,ltd.
*/
package com.esun.rabbit2.viewer.mainact.mylotteryact.accountdetail;

import java.util.ArrayList;
import java.util.Hashtable;

import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AbsListView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;

import com.esun.config.Config;
import com.esun.config.Key;
import com.esun.config.Language;
import com.esun.model.AccountDetailListInfo;
import com.esun.network.ConnectionChangeReceiver;
import com.esun.rabbit2.communicaters.accountdetail.AccountDetailListCommunicater;
import com.esun.rabbit2.viewer.mainact.lotteryinfoact.PullToRefreshListView;
import com.esun.rabbit2.viewer.mainact.lotteryinfoact.PullToRefreshListView.OnRefreshListener;
import com.esun.ui.R;
import com.esun.util.ViewerUtil;
import com.esun.util.log.EDebug;

/** 
 * @ClassName: ChargeListAct 
 * @Description: TODO(账户明细充值列表activity) 
 * @Author: Billy qigs@500wan.com
 * @Date: 2011-7-27 下午04:48:59 
 */
public class ChargeListAct extends Activity implements OnItemClickListener,OnRefreshListener,OnScrollListener{

	private AccountDetailListCommunicater accountCommunicater;
	private PullToRefreshListView listViewAccountList;
	private ProgressDialog progressDialog;
	private LinearLayout linearFooter;
	private LinearLayout linearNoMore;
	private LinearLayout linearBottom;
	private ArrayList<Hashtable<String, String>> alItem;
	private AccountDetailListAdapter adapter;
	public static Handler accountDetailHandler;
	private LinearLayout linearNoRecord;
	
	private String serverMsg;
	private int pageno = 1;
	
	private boolean isRunning = false;
	private boolean isRefreshOrBottom = true;
	private boolean isNoMoreRecord = false;
	private boolean isShow = true;
	private boolean isScrollable = true;

	private static final int GET_ACCOUNT_DETAIL_SUCCEED = 1000001;
	private static final int GET_ACCOUNT_DETAIL_FAILED = 1000002;
	private static final String CHARGE_ACCOUNT_LIST = "-1";
	private final int FOOTER_VIEW_TAG = 10000;
	private final int FOOTER_VIEW_TAG2 = 20000;
	private final int FOOTER_VIEW_TAG3 = 30000;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.accountdetaillist_act_charge);
		
		initUI();
		initHandler();
	}
	
	public void initUI(){
		
		progressDialog = ViewerUtil.showProgressDialog(ChargeListAct.this, "加载中,请稍后...");
		progressDialog.show();
		linearNoRecord = (LinearLayout)findViewById(R.id.accountdetaillist_act_charge_linear_noRecord);
		listViewAccountList = (PullToRefreshListView)findViewById(R.id.accountdetaillist_act_charge_listview_total);
		linearFooter = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.lotteryinfoact_linear_footer, null);
		linearNoMore = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.lotteryrecordlist_act_linear_nomore, null);
		linearBottom = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.listview_bottom_view, null);
		linearFooter.setTag(FOOTER_VIEW_TAG);
		linearNoMore.setTag(FOOTER_VIEW_TAG2);
		linearBottom.setTag(FOOTER_VIEW_TAG3);
		
		alItem = new ArrayList<Hashtable<String,String>>();
		adapter = new AccountDetailListAdapter(ChargeListAct.this, alItem);
		listViewAccountList.addFooterView(linearFooter);
		listViewAccountList.setAdapter(adapter);
		listViewAccountList.removeFooterView(linearFooter);
		listViewAccountList.setOnItemClickListener(this);
		listViewAccountList.setOnRefreshListener(this);
		listViewAccountList.setOnScrollListener(this);
		
//		listViewAccountList.onRefresh();
	}
	
	public void initHandler(){
		accountDetailHandler = new Handler(){

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				listViewAccountList.removeFooterView(linearBottom);
				switch(msg.what){
				
				case GET_ACCOUNT_DETAIL_SUCCEED:
					
					pageno++;
					infoHandling(accountCommunicater.getAccountDetailList());
					EDebug.o(this,"通讯成功!"+pageno);
					if(accountCommunicater.getListResult().size() < 10){
						isNoMoreRecord = false;
						listViewAccountList.addFooterView(linearNoMore);
					}
					lengthAutoAdapter();
					endProcess();
					
					break;
					
				case GET_ACCOUNT_DETAIL_FAILED:
					
					EDebug.o(this,"通讯失败！");
					isScrollable = false;
					lengthAutoAdapter();
					endProcess();
					//无更多记录
					if (accountCommunicater.getState() == 202 || accountCommunicater.getState() == 101) {
						isNoMoreRecord = false;
						if (pageno == 1) {
//							alItem.clear();
							linearNoRecord.setVisibility(View.VISIBLE);
						} else {
							listViewAccountList.addFooterView(linearNoMore);
						}
					} else {
						//通讯失败
						if (isShow) {
//							ViewerUtil.showTipDialog(ChargeListAct.this,serverMsg, false);
							Toast.makeText(ChargeListAct.this, serverMsg, 0).show();
						}
					}
					
					break;
					
				case Config.CONNECTION_FAIL:
					
					lengthAutoAdapter();
					endProcess();
					EDebug.o(this,"连接失败！");
					isScrollable = false;
					showNoMoreRecordDialog(Language.STR_CONNECTIONFAIL);
					
					break;
					
				case Config.DO_REFRESH:
					
					if(!isRunning){
						listViewAccountList.prepareForRefresh();
						listViewAccountList.onRefresh();
						progressDialog.show();						
					}
					AccountDetailListActGroup.isCanClick = true;
					break;
					
				default :
					
					break;
				}
			}
		};
	}
	
	private void endProcess(){
		if (isRefreshOrBottom) {
			listViewAccountList.onRefreshComplete();
		} else {
			listViewAccountList.removeFooterView(linearFooter);
		}
		if (progressDialog != null) {
			progressDialog.cancel();
		}
		isRunning = false;
	}
	
	public void getAccountDetailListThread(){
		new Thread(){

			@Override
			public void run() {
				// TODO Auto-generated method stub
				super.run();
				accountCommunicater = new AccountDetailListCommunicater();
				Message msg = new Message();
				try{
					boolean isSucceed = accountCommunicater.isGetAccountDetailList(CHARGE_ACCOUNT_LIST,String.valueOf(pageno));
					serverMsg = accountCommunicater.getErrorMSG();
					EDebug.o(this,accountCommunicater.getServerMsg());
					if(isSucceed){
						msg = accountDetailHandler.obtainMessage(GET_ACCOUNT_DETAIL_SUCCEED, null);
						accountDetailHandler.sendMessage(msg);
					}else{
						msg = accountDetailHandler.obtainMessage(GET_ACCOUNT_DETAIL_FAILED, null);
						accountDetailHandler.sendMessage(msg);
					}
				}catch (Exception e) {
					// TODO: handle exception
					msg = accountDetailHandler.obtainMessage(Config.CONNECTION_FAIL, null);
					accountDetailHandler.sendMessage(msg);
				}
			}
		}.start();
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		// TODO Auto-generated method stub
		if (firstVisibleItem + visibleItemCount == totalItemCount) {
			if (isNoMoreRecord) {
				if (!isRunning && alItem.size() != 0 && isScrollable) {
					EDebug.o(this,"到底加载...");
					isRunning = true;
					listViewAccountList.addFooterView(linearFooter);
					isRefreshOrBottom = false;
					getAccountDetailListThread();
				}
			}
		} else {
			isScrollable = true;
		}
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		// TODO Auto-generated method stub
	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		if(!isRunning){
			EDebug.o(this,"刷新...");
			pageno = 1;
			groupCount = 0;
			childCount = 0;
			isRunning = true;
			isNoMoreRecord = true;
			isRefreshOrBottom = true;
			linearNoRecord.setVisibility(View.GONE);
			if(listViewAccountList.getFooterViewsCount() != 0){
				listViewAccountList.removeFooterView(linearNoMore);
			}
			getAccountDetailListThread();
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
	}
	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		isShow = false;
		this.unregisterReceiver(ConnectionChangeReceiver.getConnectionChangeReceiver());
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		isShow = true;
		this.registerReceiver(ConnectionChangeReceiver.getConnectionChangeReceiver(), ConnectionChangeReceiver.getIntentFilter());
	}

	/*显示提示框**/
	public void showNoMoreRecordDialog(String strMsg){
		if(isShow){
			ViewerUtil.showTipDialog(ChargeListAct.this, strMsg, false);
		}
	}
	
	public void infoHandling(ArrayList<AccountDetailListInfo> list){
		ArrayList<Hashtable<String, String>> listTemp = new ArrayList<Hashtable<String,String>>();
		for(int i = 0;i < list.size();i++){
			Hashtable<String, String> map = new Hashtable<String, String>();
			
			String [] strDate = list.get(i).getOpTime().split(" ");
			
			map.put(Key.KEY_DATE, strDate[0]);
			map.put(Key.KEY_TIME, strDate[1]);
			map.put(Key.KEY_INOUT, list.get(i).getOpType());
			map.put(Key.KEY_MONEY, list.get(i).getMoney());
			map.put(Key.KEY_BALANCE, list.get(i).getBalance());
			map.put(Key.KEY_LOTID, list.get(i).getLotType());
			map.put(Key.KEY_NOTE, list.get(i).getNote());
			map.put(Key.KEY_TYPEID, list.get(i).getTypeID());
			map.put(Key.KEY_REMARK, list.get(i).getRemarks());
			map.put(Key.KEY_PID, list.get(i).getPid());
//			map.put("state", list.get(i).getState());
			
			listTemp.add(map);
		}
		
		if(isRefreshOrBottom){
			alItem.clear();
			alItem.addAll(listTemp);
			adapter.notifyDataSetChanged();
		}else{
			alItem.addAll(listTemp);
			adapter.notifyDataSetChanged();
		}
	}
	
	private int groupCount = 0;
	private int childCount = 0;

	private void lengthAutoAdapter() {
		adapter.countCalculate();
		groupCount = adapter.getGroupCount();
		childCount = adapter.getChildCount();

		int itemHeight = groupCount * (30+90) + childCount * 90;
		//判断是否需要加入额外item
		if (itemHeight < listViewAccountList.getHeight()) {
			LinearLayout linearChild = new LinearLayout(this);
			int bheight = 0;
			linearChild.setBackgroundColor(Color.WHITE);
			if(listViewAccountList.getFooterViewsCount() > 0){
				bheight = listViewAccountList.getHeight() - itemHeight - 30;
			}else{
				bheight = listViewAccountList.getHeight() - itemHeight;
			}
			linearBottom.addView(linearChild);
			for (int i = 0; i < linearBottom.getChildCount(); i++) {
				linearBottom.getChildAt(i).getLayoutParams().height = bheight;
				linearBottom.getChildAt(i).getLayoutParams().width = LayoutParams.FILL_PARENT;
			}
			linearChild.setBackgroundColor(Color.WHITE);
			listViewAccountList.addFooterView(linearBottom);
		}
	}
}
